package com.lele.config.security;

import com.lele.pojo.Menu;
import com.lele.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

/**
 * 当前登录的请求需要哪些角色
 */
@Component
public class CustomerFilter implements FilterInvocationSecurityMetadataSource {
    @Autowired
    private IMenuService menuService;
    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        //获取到登录请求的url
        String url = ((FilterInvocation) object).getRequestUrl();
        List<Menu> menuList = menuService.getMenuWithRole();
        for (Menu menu : menuList) {
            if (antPathMatcher.match(menu.getUrl(), url)) {
                String[] strings = menu.getRoles().stream().map(it -> {
                    return it.getName();
                }).toArray(String[]::new);
                //转换为
                return SecurityConfig.createList(strings);
            }
        }
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
